<template>
  <div class="favorite-detail">
    <div class="page-header">
      <el-button :icon="ArrowLeft" @click="$router.back()">返回</el-button>
      <div class="header-actions">
        <el-button :icon="Edit" @click="handleEdit">编辑</el-button>
        <el-button
          :type="item?.isFavorite ? 'warning' : 'info'"
          :icon="item?.isFavorite ? StarFilled : Star"
          @click="handleToggleFavorite"
        >
          {{ item?.isFavorite ? '取消收藏' : '收藏' }}
        </el-button>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <el-skeleton :rows="8" animated />
    </div>

    <div v-else-if="item" class="detail-content">
      <!-- 标题和基本信息 -->
      <div class="detail-header">
        <h1 class="detail-title">{{ item.title }}</h1>
        <div class="detail-meta">
          <el-tag :type="getTypeTagType(item.type)" size="large">
            <el-icon style="margin-right: 4px;">
              <component :is="getTypeIcon(item.type)" />
            </el-icon>
            {{ getTypeText(item.type) }}
          </el-tag>
          <el-tag v-if="item.categoryName" type="info" size="large">
            {{ item.categoryName }}
          </el-tag>
        </div>
      </div>

      <!-- 封面图片 -->
      <div v-if="item.imageUrl" class="detail-image">
        <img :src="item.imageUrl" :alt="item.title" @error="handleImageError" />
      </div>

      <!-- 内容区域 -->
      <div class="detail-body">
        <!-- 描述 -->
        <div v-if="item.description" class="detail-section">
          <h3>描述</h3>
          <p class="description-text">{{ item.description }}</p>
        </div>

        <!-- 文本内容 -->
        <div v-if="item.content && item.type === 'text'" class="detail-section">
          <div class="content-markdown">
            <MarkdownRenderer :content="item.content" theme="classic" />
          </div>
        </div>

        <!-- 链接 -->
        <div v-if="item.url" class="detail-section">
          <h3>{{ getLinkSectionTitle(item.type) }}</h3>
          <div class="link-section">
            <el-link :href="item.url" target="_blank" type="primary" :underline="false">
              <el-icon style="margin-right: 8px;"><Link /></el-icon>
              {{ item.url }}
            </el-link>
            <el-button 
              size="small" 
              type="primary" 
              @click="copyToClipboard(item.url)"
              style="margin-left: 12px;"
            >
              复制链接
            </el-button>
          </div>
        </div>

        <!-- 标签 -->
        <div v-if="item.tags && item.tags.length > 0" class="detail-section">
          <h3>标签</h3>
          <div class="tags-container">
            <el-tag
              v-for="tag in item.tags"
              :key="tag"
              type="info"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>

        <!-- 元信息 -->
        <div class="detail-section">
          <h3>详细信息</h3>
          <div class="meta-info">
            <div v-if="item.source" class="meta-item">
              <span class="meta-label">出处：</span>
              <span class="meta-value">{{ item.source }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">创建时间：</span>
              <span class="meta-value">{{ formatDateTime(item.createdAt) }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">更新时间：</span>
              <span class="meta-value">{{ formatDateTime(item.updatedAt) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="error-state">
      <el-empty description="收藏项不存在或已被删除">
        <el-button type="primary" @click="$router.push('/favorites')">
          返回收藏列表
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Edit,
  StarFilled,
  Star,
  Link,
  Document,
  VideoPlay,
  Picture
} from '@element-plus/icons-vue'
import { favoriteItemApi } from '../api'
import type { FavoriteItem } from '../types'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const item = ref<FavoriteItem | null>(null)

// 获取类型图标
const getTypeIcon = (type: string) => {
  switch (type) {
    case 'text':
      return Document
    case 'link':
      return Link
    case 'image':
      return Picture
    case 'video':
      return VideoPlay
    default:
      return Document
  }
}

// 获取类型文本
const getTypeText = (type: string) => {
  switch (type) {
    case 'text':
      return '文本/佳句'
    case 'link':
      return '链接'
    case 'image':
      return '图片'
    case 'video':
      return '视频'
    default:
      return '文本'
  }
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  switch (type) {
    case 'text':
      return 'primary'
    case 'link':
      return 'info'
    case 'image':
      return 'success'
    case 'video':
      return 'warning'
    default:
      return 'primary'
  }
}

// 获取链接区域标题
const getLinkSectionTitle = (type: string) => {
  switch (type) {
    case 'link':
      return '链接地址'
    case 'image':
      return '图片地址'
    case 'video':
      return '视频地址'
    default:
      return '链接'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 处理图片错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 处理编辑
const handleEdit = () => {
  if (item.value) {
    router.push(`/favorites/edit/${item.value.id}`)
  }
}

// 处理切换收藏状态
const handleToggleFavorite = async () => {
  if (!item.value) return
  
  try {
    await favoriteItemApi.toggleFavorite(item.value.id)
    item.value.isFavorite = !item.value.isFavorite
    ElMessage.success(item.value.isFavorite ? '已收藏' : '已取消收藏')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 加载收藏项详情
const loadFavoriteItem = async () => {
  const id = route.params.id as string
  if (!id) {
    ElMessage.error('收藏项ID不能为空')
    router.push('/favorites')
    return
  }

  try {
    item.value = await favoriteItemApi.getDetail(id)
  } catch (error) {
    ElMessage.error('加载收藏项失败')
    item.value = null
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  loadFavoriteItem()
})
</script>

<style scoped>
.favorite-detail {
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.loading-state {
  padding: 24px;
}

.error-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.detail-content {
  width: 100%;
}

.detail-header {
  padding: 24px 24px 0 24px;
}

.detail-title {
  font-size: 28px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 16px 0;
  line-height: 1.4;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.view-count {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.detail-image {
  padding: 0 24px;
  margin: 24px 0;
}

.detail-image img {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);
}

.detail-body {
  padding: 0 24px 24px 24px;
}

.detail-section {
  margin-bottom: 32px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.detail-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 16px 0;
  border-bottom: 2px solid var(--el-color-primary);
  padding-bottom: 8px;
}

.description-text {
  font-size: 16px;
  color: var(--el-text-color-regular);
  line-height: 1.6;
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.content-markdown {
  font-size: 16px;
  color: var(--el-text-color-primary);
  line-height: 1.8;
  margin: 0;
  padding: 20px;
  background: var(--el-fill-color-light);
  border-left: 4px solid var(--el-color-primary);
  border-radius: 0 8px 8px 0;
}

.link-section {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  font-size: 14px;
}

.meta-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-label {
  font-weight: 600;
  color: var(--el-text-color-regular);
  min-width: 80px;
}

.meta-value {
  color: var(--el-text-color-primary);
}

/* 深色模式适配 */
.dark .content-markdown {
  background: var(--el-fill-color);
  border-color: var(--el-color-primary);
}

.dark .detail-image img {
  border-color: var(--el-border-color);
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .detail-header,
  .detail-image,
  .detail-body {
    padding-left: 16px;
    padding-right: 16px;
  }
  
  .detail-title {
    font-size: 24px;
  }
  
  .meta-info {
    grid-template-columns: 1fr;
  }
  
  .link-section {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>